const {
  app,
  Menu,
  ipcMain,
  dialog
} = require('electron')
const path = require('path')
const isDev = require('electron-is-dev') // 判断是否处于开发模式中
const menuTemplate = require('./menuTemplate') // 菜单项
const AppWindow = require('./src/AppWindow') // 封装的BrowerWidnow类
const QiniuManager = require('./src/utils/QiniuManager')
const Store = require('electron-store')
const fileStore = new Store({
  name: 'Files Data'
})
const settingsStore = new Store({ // 配置store
  name: 'Settings'
})

let mainWindow, settingsWindow // 窗口名称
const createManager = () => {
  const accessKey = settingsStore.get('accessKey')
  const secretKey = settingsStore.get('secretKey')
  const bucketName = settingsStore.get('bucketName')
  const domainURL = settingsStore.get('domainURL')
  return new QiniuManager(accessKey, secretKey, bucketName, domainURL)
}

app.on('ready', () => {
  const mainWindowConfig = {
    width: 1440,
    height: 768,
    autoHideMenuBar: true
  }

  const urlLocation = isDev ? 'http://localhost:3000' : 'dummyurl'
  mainWindow = new AppWindow(mainWindowConfig, urlLocation)
  mainWindow.on('closed', () => {
    mainWindow = null;
  })
  // 原生菜单项
  const menu = Menu.buildFromTemplate(menuTemplate)
  Menu.setApplicationMenu(menu)

  // 弹出的设置窗口
  ipcMain.on('open-settings-window', () => {
    const settingsWindowConfig = {
      width: 720,
      height: 520,
      frame: false, // 设置无边框
      transparent: true, // 设置其父窗口透明
      resizable: false, // 设置不能改变窗口大小
      parent: mainWindow
    }
    const settingsFileLocation = `file://${path.join(__dirname, './settings/settings.html')}`;
    settingsWindow = new AppWindow(settingsWindowConfig, settingsFileLocation);

    settingsWindow.on('closed', () => {
      settingsWindow = null;
    })
  })
  // 控制设置窗口的关闭和缩小
  ipcMain.on('close', e =>
    settingsWindow.close()
  )
  ipcMain.on('minimize', e =>
    settingsWindow.minimize()
  )

  // 发送文件到云端
  ipcMain.on('upload-file', (event, data) => {
    const manager = createManager()
    manager.uploadFile(data.key, data.path).then(data => {
      console.log('上传成功', data)
      mainWindow.webContents.send('active-file-uploaded')
    }).catch(err => {
      dialog.showErrorBox('同步失败', '请检查七牛云参数是否正确')
    })
  })

  // 更新配置后的菜单状态
  ipcMain.on('config-is-saved', () => {
    let qiniuMenu = process.platform === 'darwin' ? menu.items[3] : menu.items[2]
    const switchItems = (toggle) => {
      [1, 2, 3].forEach(number => {
        qiniuMenu.submenu.items[number].enabled = toggle
      })
    }
    const qiniuIsConfiged = ['accessKey', 'secretKey', 'bucketName', 'domainURL'].every(key => !!settingsStore.get(key))
    switchItems(qiniuIsConfiged)
  })

  // 下载文件
  ipcMain.on('download-file', (event, data) => {
    const manager = createManager();
    const filesObj = fileStore.get('files')
    const {
      key,
      path,
      id
    } = data
    manager.getState(data.key).then(resp => {
      const serverUpdatedTime = Math.round(resp.putTime / 10000) // 云端时间
      const localUpdatedTime = filesObj[id].updatedAt // 本地时间
      // 当云端时间大于本地时间（云端文件被修改）
      // 当本地时间不存在，说明该文件从未上传到云端
      if (serverUpdatedTime > localUpdatedTime || !localUpdatedTime) {
        manager.downloadFile(key, path).then(() => {
          mainWindow.webContents.send('file-downloaded', {
            status: 'download-success',
            id
          })
        })
      } else {
        mainWindow.webContents.send('file-downloaded', {
          status: 'no-new-success',
          id
        })
      }
    }, err => {
      if (err.code === 612) {
        mainWindow.webContents.send('file-downloaded', {
          status: 'no-file',
          id
        })
      }
    })

    // 上传全部文件到云端
    ipcMain.on('upload-all-to-qiniu', ()=>{
      console.log('xxxx1')
      mainWindow.webContents.send('loading-status', true)
      setTimeout(() => {
        mainWindow.webContents.send('loading-status', false)
      }, 2000);
    })
  })
})